/**
 *
 * jcrt and its source-code is licensed under the LGPL.
 * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
 * When copying, adapting, or redistributing this document in keeping with the guidelines above,
 * you are required to provide proper attribution to obinary.
 * If you reproduce or distribute the document without making any substantive modifications to its content,
 * please use the following attribution line:
 *
 * Copyright 2007 Atjava.com Ltd. (http://www.atjava.com) All rights reserved.
 *
 */
package com.atjava.jcrt.core;

import org.apache.log4j.Logger;

import com.atjava.jcrt.JcrtSessionFactory;
import com.atjava.jcrt.JcrtSession;
import com.atjava.jcrt.core.exception.CoreException;
import com.atjava.jcrt.core.transaction.XmlJcrtInfo;
import com.atjava.jcrt.core.transaction.XmlServices;
import com.atjava.jcrt.repository.Provider;
import com.atjava.jcrt.repository.RepositoryNotInitializedException;

/**
 * JcrtManagerFactoryImpl
 * 
 * @author biggie
 * @version $Revision: 1.2 $ $Date: 2008/07/23 07:18:38 $
 */
public class JcrtSessionFactoryImpl extends JcrtSessionFactory {

	private Provider provider = null;
	private XmlServices xmlServices  = null;
	
	private static Logger log = Logger.getLogger (XmlServices.class.getName()) ;
	@Override
	public void startServices() throws CoreException {
		//Get Provider
		if(xmlServices == null){
			xmlServices = XmlServices.getInstance();
		}
		if (getConfigurationfile() != null)
			xmlServices.setConfigurationfile(getConfigurationfile());
		
		xmlServices.startService();
		
		if(provider == null){
			try {
				provider = (Provider)(Class.forName(xmlServices.getXmlJcrtInfo().getRepositoryprovider()).newInstance());
				provider.init(xmlServices.getXmlJcrtInfo());
			} catch (InstantiationException e) {
				log.error("Create Provider Instace Error",e);
				throw new CoreException(e);
			} catch (IllegalAccessException e) {
				log.error("Create Provider Instace Error",e);
				throw new CoreException(e);
			} catch (ClassNotFoundException e) {
				log.error("Create Provider Instace Error",e);
				throw new CoreException(e);
			}catch (RepositoryNotInitializedException e){
				log.error("Create Provider Instace Error",e);
				throw new CoreException(e);
			}
		}
		//Over
		setStartServiceFlag(true);
	}

	@Override
	public JcrtSession openJcrtSession() throws CoreException {
		return new JcrtSessionImpl(this.provider,this.xmlServices.getXmlJcrtInfo());
	}

	@Override
	public Provider getProvider() throws CoreException {
		return this.provider;
	}

	@Override
	public JcrtSession openJcrtSession(String workspace) throws CoreException {
		return new JcrtSessionImpl(this.provider,this.xmlServices.getXmlJcrtInfo(),workspace);
	}

	@Override
	public XmlJcrtInfo getXmlJcrtInfo() throws CoreException {
		return this.xmlServices.getXmlJcrtInfo();
	}
	
}
